﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Samples.ServiceHosting.StorageClient;
using System.Data.Services.Client;
using System.Net;
using System.Globalization;

namespace Inscription_WebRole
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            StorageAccountInfo account = null;

            try
            {
                //Identification
                account = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration();
                DataServiceContext svc = new DataServiceContext(account);
                svc.RetryPolicy = RetryPolicies.RetryN(3, TimeSpan.FromSeconds(1));


                var qResult = from c in svc.InscriptionTable
                              select c;

                TableStorageDataServiceQuery<Inscription> q = new TableStorageDataServiceQuery<Inscription>(qResult as DataServiceQuery<Inscription>, svc.RetryPolicy);

                try
                { 
                    // This query can generate an exception if there are 0 results during enumeration
                    IEnumerable<Inscription> res = q.ExecuteAllWithRetries();
                    
                    
                    suscribersGV.DataSource = res.ToList();
                    suscribersGV.DataBind();
                }
                catch (DataServiceQueryException ex)
                {
                    HttpStatusCode s;

                    if (TableStorageHelpers.EvaluateException(ex, out s) && s == HttpStatusCode.NotFound)
                    {
                        // The entity was not found
                        errorLbl.Text  = "The entity was not found. This is expected here.";
                    }
                }
            }
            catch (DataServiceRequestException dsre)
            {
                Console.WriteLine("DataServiceRequestException: " + GetExceptionMessage(dsre));
                ShowTableStorageErrorMessage(account.BaseUri.ToString());
            }
            catch (InvalidOperationException ioe)
            {
                System.Diagnostics.Debug.WriteLine("Storage service error: " + GetExceptionMessage(ioe));
                ShowTableStorageErrorMessage(account.BaseUri.ToString());
            }
        }

        private static void ShowTableStorageErrorMessage(string endpoint)
        {
            System.Diagnostics.Debug.WriteLine("Please check if the table storage service is running at " + endpoint);
            System.Diagnostics.Debug.WriteLine("Detailed information on how to run the development table storage tool " +
                              "locally can be found in the readme file that comes with this sample.");
            System.Diagnostics.Debug.WriteLine("Also make sure that you started the table service with the right parameters, " +
                              "that is, exactly as described in the readme file for this sample.");
        }

        private static string GetExceptionMessage(Exception exception)
        {
            HttpStatusCode statusCode;
            StorageExtendedErrorInformation extendedErrorInfo;
            if (TableStorageHelpers.EvaluateException(exception, out statusCode, out extendedErrorInfo))
            {
                if (extendedErrorInfo != null)
                {
                    return string.Format(CultureInfo.InvariantCulture, "{0} {1}", extendedErrorInfo.ErrorCode ?? "", extendedErrorInfo.ErrorMessage ?? "");
                }
            }

            DataServiceClientException dse = exception.InnerException as DataServiceClientException;
            if (dse != null)
                return dse.Message;
            else
                return exception.Message;
        }
    }
}
